﻿using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
using ORS.OrderRobot.Helper;
using ORS.OrderRobot.Service.Tasker;
using ORS.OrderRobot.ServiceContracts;

namespace ORS.OrderRobot.Service
{
	public class MessageHub:Hub
	{
        private readonly IServiceProvider _serviceProvider;
        // 通过构造函数注入IServiceProvider
        public MessageHub(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }
        /// <summary>
        /// 由前端调用的Send方法
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendMessage(string message, string messageType = "info")
        {
            await Clients.All.SendAsync("ReceiveMessage", message, messageType);
        }
        /// <summary>
        /// 客户端连接时发送的消息
        /// </summary>
        /// <returns></returns>
        public override async Task OnConnectedAsync()
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                var systemConfigService = scope.ServiceProvider.GetRequiredService<ISystemConfigService>();
                var autoShoppingTasker =  scope.ServiceProvider.GetRequiredService<AutoShoppingTasker>();
                var config = await systemConfigService.GetConfigAsync();
                var productTask = config.MointerProductTask;
                var shopTask = config.AutoShoppingTask;
                var message = $"""
                商品扫描: {(productTask.Disabled ? "禁用" : "启用")} 时间段: {productTask.StartTime?.ToString() ?? "无限制"}-{productTask.EndTime?.ToString() ?? "无限制"}
                自动下单: {(config.AutoShoppingTask.Disabled ? "禁用" : "启用")} 时间段: {shopTask.StartTime?.ToString() ?? "无限制"}-{shopTask.EndTime?.ToString() ?? "无限制"}
                下单器状态:{autoShoppingTasker.TaskInfo.Id} {EnumHelper.GetEnumDescription(autoShoppingTasker.TaskInfo.Status)}
                """;
                await Clients.All.SendAsync(Consts.SignalRMethod, message,"system",DateTime.Now.China(),"low");
                // 如果需要，你也可以在这里向其他用户发送消息
                //await Clients.All.SendAsync("Notify", "新用户已连接！");
            }
            await base.OnConnectedAsync();
        }
    }
}

